import 'package:date_format/date_format.dart';

class DateUtil {
  static String dateStrFormat(String dateStr, List<String> formats) {
    //DateTime转时间戳
    return secondsFormat(
        DateTime.parse(dateStr).millisecondsSinceEpoch, formats);
  }

  ///时间戳格式化时间
  static String secondsFormat(int unix, List<String> formats) {
    //时间戳转DateTime
    DateTime dateTime = DateTime.fromMillisecondsSinceEpoch(unix, isUtc: false);
    print('datetime:${dateTime.toString()}');
    StringBuffer sb = StringBuffer();
    if (formats[0] == HH) {
      for (String format in formats) {
        if (format == HH) {
          sb.write(digits(dateTime.hour - 8, 2));
        } else if (format == nn) {
          sb.write(digits(dateTime.minute, 2));
        } else if (format == ss) {
          sb.write(digits(dateTime.second, 2));
        } else {
          sb.write(format);
        }
      }
    } else if (formats[0] == nn) {
      for (String format in formats) {
        if (format == nn) {
          sb.write(digits((dateTime.hour - 8) * 60 + dateTime.minute, 2));
        } else if (format == ss) {
          sb.write(digits(dateTime.second, 2));
        } else {
          sb.write(format);
        }
      }
    } else if (formats[0] == yyyy) {
      for (String format in formats) {
        if (format == yyyy) {
          sb.write(dateTime.year);
        } else if (format == mm || format == MM) {
          sb.write(digits(dateTime.month, 2));
        } else if (format == dd) {
          sb.write(digits(dateTime.day, 2));
        } else if (format == HH) {
          sb.write(digits(dateTime.hour - 8, 2));
        } else if (format == nn) {
          sb.write(digits(dateTime.minute, 2));
        } else if (format == ss) {
          sb.write(digits(dateTime.second, 2));
        } else {
          sb.write(format);
        }
      }
    }
    return sb.toString();
  }

  static String digits(int value, int length) {
    String ret = '$value';
    if (ret.length < length) {
      ret = '0' * (length - ret.length) + ret;
    }
    return ret;
  }
}
